package com.neo.tiny.demo.sso.config.security.filter;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.neo.tiny.demo.sso.api.OauthApi;
import com.neo.tiny.demo.sso.dto.OAuth2CheckTokenRespDTO;
import com.neo.tiny.demo.sso.config.security.context.TokenAuthentication;
import com.neo.tiny.demo.sso.config.security.model.AdminUserDetails;
import com.neo.tiny.demo.sso.util.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description:
 * @Author: yqz
 * @CreateDate: 2022/11/13 16:31
 */
@Slf4j
@Component
public class AuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private OauthApi oauthApi;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {

        String token = SecurityUtils.obtainHeaderToken(request);
        if (StrUtil.isNotBlank(token)) {
            // 根据token 获取用户信息
            OAuth2CheckTokenRespDTO dto = oauthApi.checkAccessToken(token).getData();
            if (BeanUtil.isNotEmpty(dto)) {
                AdminUserDetails userDetails = new AdminUserDetails(dto.getUserId(), dto.getUserName(), dto.getUserType(), dto.getScopes(), dto.getAccessToken());
                // 普通用户
                TokenAuthentication tokenAuthentication = new TokenAuthentication(userDetails, userDetails,
                        dto.getUserType(), dto.getClientId());
                tokenAuthentication.setAuthenticated(true);
                tokenAuthentication.setAuthorities(userDetails.getAuthorities());
                log.error("已认证的用户：{}", dto.getUserName());
                //重新把认证添加到上下文中
                SecurityContextHolder.getContext().setAuthentication(tokenAuthentication);
            }
        }
        filterChain.doFilter(request, response);
    }
}
